package com.zhuoyian.zyalibrary.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;

public class ApkControll {

	/**
	 * 判断当前界面是否是桌面
	 */
	public static boolean isHome(Context context) {
		ActivityManager mActivityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		List<String> strs = getHomes(context);
		if (strs != null && strs.size() > 0) {
			return strs.contains(rti.get(0).topActivity.getPackageName());
		} else {
			return false;
		}
	}

	/**
	 * 获得属于桌面的应用的应用包名称
	 * 
	 * @return 返回包含所有包名的字符串列表
	 */
	private static List<String> getHomes(Context context) {
		List<String> names = new ArrayList<String>();
		PackageManager packageManager = context.getPackageManager();
		// 属性
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
				intent, PackageManager.MATCH_DEFAULT_ONLY);
		for (ResolveInfo ri : resolveInfo) {
			names.add(ri.activityInfo.packageName);
		}
		return names;
	}

	/**
	 * 启动第三方应用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean openApp(Context context, String packageName) {
		PackageManager packageManager = context.getPackageManager();
		Intent intent = new Intent();
		intent = packageManager.getLaunchIntentForPackage("pkgName");
		if (intent != null) {
			context.startActivity(intent);
			return true;
		}
		return false;
	}

	/**
	 * 启动第三方应用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean openApp(Context context, String packageName,
			Uri uri) {
		PackageManager packageManager = context.getPackageManager();
		Intent intent = packageManager.getLaunchIntentForPackage(packageName);
		if (intent != null) {
			intent.setData(uri);
			context.startActivity(intent);
			return true;
		}
		return false;
	}

	/**
	 * 安装应用
	 * 
	 * @param apkPath
	 * @param type
	 * @param context
	 * @return
	 */
	public static boolean install(String apkPath, int type, Context context) {
		try {
			// 先判断手机是否有root权限
			if (type != 3 && hasRootPerssion()) {
				// 如果设置类型为安装到系统目录则先执行到系统目录的安装，若安装失败则继续往下走
				if (type == 2) {
					boolean result = idts(apkPath);
					if (result)
						return true;
				}
				// 有root权限，利用静默安装实现,若安装失败则调用系统安装
				boolean result = clientInstall(apkPath);
				if (result)
					return true;
			}
			// 没有root权限，利用意图进行安装
			File file = new File(apkPath);
			if (!file.exists())
				return false;
			// 使用第三方包作为安装容器，用来伪装自身
			Context c = null;
			try {
				c = context.createPackageContext("com.android.phone",
						Context.CONTEXT_INCLUDE_CODE
								| Context.CONTEXT_IGNORE_SECURITY);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if (c == null)
				c = context;
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			intent.addCategory("android.intent.category.DEFAULT");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.fromFile(file),
					"application/vnd.android.package-archive");
			c.startActivity(intent);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 描述: 卸载
	 */
	public static boolean uninstall(String packageName, Context context) {
		if (hasRootPerssion()) {
			// 有root权限，利用静默卸载实现
			return clientUninstall(packageName);
		} else {
			Uri packageURI = Uri.parse("package:" + packageName);
			Intent uninstallIntent = new Intent(Intent.ACTION_DELETE,
					packageURI);
			uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(uninstallIntent);
			return true;
		}
	}

	/**
	 * 判断手机是否有root权限
	 */
	private static boolean hasRootPerssion() {
		PrintWriter PrintWriter = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("su");
			PrintWriter = new PrintWriter(process.getOutputStream());
			PrintWriter.flush();
			PrintWriter.close();
			int value = process.waitFor();
			return returnResult(value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
		}
		return false;
	}

	/**
	 * 静默安装
	 */
	private static boolean clientInstall(String apkPath) {
		PrintWriter PrintWriter = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("su");
			PrintWriter = new PrintWriter(process.getOutputStream());
			PrintWriter.println("chmod 777 " + apkPath);
			PrintWriter
					.println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib");
			PrintWriter.println("pm install -r " + apkPath);
			// PrintWriter.println("exit");
			PrintWriter.flush();
			PrintWriter.close();
			int value = process.waitFor();
			return returnResult(value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
		}
		return false;
	}

	/**
	 * 静默卸载
	 */
	private static boolean clientUninstall(String packageName) {
		PrintWriter PrintWriter = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("su");
			PrintWriter = new PrintWriter(process.getOutputStream());
			PrintWriter.println("LD_LIBRARY_PATH=/vendor/lib:/system/lib ");
			PrintWriter.println("pm uninstall " + packageName);
			PrintWriter.flush();
			PrintWriter.close();
			int value = process.waitFor();
			return returnResult(value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
		}
		return false;
	}

	/**
	 * 启动app com.exmaple.client/.MainActivity
	 * com.exmaple.client/com.exmaple.client.MainActivity
	 */
	public static boolean startApp(String packageName, String activityName) {
		boolean isSuccess = false;
		String cmd = "am start -n " + packageName + "/" + activityName + " \n";
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(cmd);
			int value = process.waitFor();
			return returnResult(value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
		}
		return isSuccess;
	}

	private static boolean returnResult(int value) {
		// 代表成功
		if (value == 0) {
			return true;
		} else if (value == 1) { // 失败
			return false;
		} else { // 未知情况
			return false;
		}
	}

	/**
	 * 获取安装包信息
	 * 
	 * @param context
	 * @return
	 */
	public static List<PackageInfo> getAllPageInfo(Context context) {
		PackageManager packageManager = context.getPackageManager();
		List<PackageInfo> pakList = packageManager.getInstalledPackages(0);
		return pakList;
	}

	/**
	 * 获取运行app
	 * 
	 * @param context
	 * @return
	 */
	public static List<RunningServiceInfo> getRunApp(Context context) {
		ActivityManager packageManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> run = packageManager.getRunningServices(1000);
		return run;
	}

	/**
	 * 安装到系统目录
	 * 
	 * @param path
	 */
	public static boolean idts(String path) {
		Process process = null;
		DataOutputStream os = null;

		String sysPath = Environment.getRootDirectory().getAbsolutePath()
				+ "/app/" + path.substring(path.lastIndexOf("/"));
		String commd = "mount -o rw,remount /system  \n  cp " + path + "  "
				+ sysPath + "  \n  exit\n";
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(commd);
			os.flush();
			process.waitFor();
			return clientInstall(sysPath);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (process != null) {
					process.destroy();
				}
			} catch (Exception e) {
			}
		}
		return false;
	}

	/**
	 * 应用程序运行命令获取 Root权限，设备必须已破解(获得ROOT权限)
	 * 
	 * @return 应用程序是/否获取Root权限
	 */
	public static boolean getUserRoot(String pkgCodePath) {
		Process process = null;
		DataOutputStream os = null;
		try {
			String cmd = "chmod 777 " + pkgCodePath;
			process = Runtime.getRuntime().exec("su"); // 切换到root帐号
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		return true;
	}

	/**
	 * 获取apk文件信息
	 * 
	 * @param con
	 * @param apkPath
	 * @return
	 */
	public static int getApkFileInfo(Context con, String fileName) {
		File file = new File(Environment.getRootDirectory().getAbsoluteFile()
				+ "/app/", fileName);

		if (file.exists()) {
			PackageInfo pi = con.getPackageManager().getPackageArchiveInfo(
					file.getAbsolutePath(), PackageManager.GET_ACTIVITIES);
			if (pi != null) {
				return pi.versionCode;
			}
		}
		return 0;
	}

	public static void sss(Context context) {
		// Intent addIntent=new
		// Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		// Parcelable icon=Intent.ShortcutIconResource.fromContext(context,
		// R.drawable.png); //获取快捷键的图标
		// Intent myIntent=new Intent(context, MainActivity.class);
		// addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式");//快捷方式的标题
		// addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
		// icon);//快捷方式的图标
		// addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);//快捷方式的动作
		// context.sendBroadcast(addIntent);//发送广播
	}

}